import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import router from '@/router/index'
import { getToken, cleanSession, getExpireTime, setStorage } from '@/utils/auth'
import { menuStore } from "@/store/menu"
import { useUserInfoStore } from "@/store/user"
import { accountMyApiGet } from "@/api/userMangement"
import { useColorStore } from "@/store/common"
import { ElMessage } from 'element-plus'

const whiteList = ['/login']; //白名单


router.beforeEach(async (to, from, next) => {
    NProgress.configure({ showSpinner: false });
    if (to.meta.title) NProgress.start();

    const mstore = menuStore()
    const userStore = useUserInfoStore()
    const commonStore = useColorStore()
    const nowTime = new Date().getTime()
    //获取token
    
    let token = getToken();
    // 直接就在外层做一个好了 
    // 判断过期时间
    if (token) {
        // 判断 过期时间  没有用户信息 但是有 token 
        console.log(to.path);
        
        if (nowTime >= Number(getExpireTime())) {
            // 登录过期 有用户和没得用户信息
            if (userStore.userInfo) {
                ElMessage({
                    message: '登录时间过期',
                    type: 'error',
                })
                mstore.clearStrore()
                userStore.clearUserInfo()
                next({ path: '/login' })
            } else {
                cleanSession()
                next({ path: '/login' })
                console.log(to.path, '登录过期 而且没有用户信息 ');
            }
        }
        // 没有用户信息 做一次登录
        if (!userStore.userInfo) {
            const userDetail = await accountMyApiGet()
            if(userDetail.code == 20000 && userDetail.data){
                userStore.setUserInfo(userDetail.data)
                await mstore.getMenuList(router)
                setStorage('targetPath', '/')
                commonStore.getProvince()
                next({ path: '/' })
            }else{
                cleanSession()
                next({ path: '/login' })
                console.log(to.path, '登录过期 而且没有用户信息 ');
            }
        }
        if (to.path === '/login' || to.path === '/') {
            NProgress.done();

            next({ path: '/' })
        } else if (mstore.menuList.length === 0) {
            // 页面在刷新 
            NProgress.done();

            try {
                // 直接使用缓存数据
                await mstore.flashRouter(router)

                router.addRoute({
                    path: '/:catchAll(.*)',
                    name: '404',
                    component: () => import('@/view/error/404.vue'),
                })
                next({ ...to, replace: true })
                // next()
            } catch (error) {
                //重置token
                cleanSession();
                //跳到登录
                next({ path: '/login' })
            }

        } else {
            next()
        }


    } else {
        NProgress.done();

        //判断是否在白名单中
        if (whiteList.indexOf(to.path) !== -1) { //存在白名单，放行
            next();
            console.log(to.path, '白名单');

        } else { //不存在，登录
            next({ path: '/login' })
            console.log(to.path, 'login');

        }
    }
})

router.onError((error, to, from) => {
    //error loading dynamically imported module
    // if (/Failed to fetch dynamically imported module|Unable to preload CSS for|error loading dynamically imported module/.test(error.message)) {
    window.history.pushState({}, '', to.path);
    window.location.reload();
    // }
});
// 路由加载后
router.afterEach(() => {
    NProgress.done();
});